/*!
 * tykhome - sign.js
 * Author tykhome <yongketian@gmail.com>
 */

/**
 * Module dependencies.
 */
var check = require('validator').check;
// sanitize = require('validator').sanitize;

var crypto = require('crypto');
var config = require('../config/config').config;

var User = require('../proxy').User;
var Notify = require('../proxy').Notify;

var Util = require('../libs/util');

/**
 * Show user login page.
 *
 * @param  {HttpRequest} req
 * @param  {HttpResponse} res
 */
exports.showLogin = function (req, res) {
	// req.session._loginReferer = req.headers.referer;
	req.session._loginReferer = req.query.backurl;
	res.render('sign/signin');
};

/**
 * define some page when login just jump to the home page
 * @type {Array}
 */
var notJump = [
	'/sign/signin', // login page
	'/sign/signup' //regist page
];

/**
 * Handle user login.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.login = function (req, res, next) {
	var email = req.body.email.trim();
	var pass = req.body.pass.trim();
	if (!email || !pass) {
		return res.render('sign/signin', {
			error: '信息不完整。'
		});
	}

	User.getUserByMail(email, function (err, user) {
		if (err) {
			return next(err);
		}
		if (!user) {
			return res.render('sign/signin', {
				error: '这个用户不存在。'
			});
		}
		pass = md5(pass);
		if (pass !== user.pass) {
			return res.render('sign/signin', {
				error: '密码错误。'
			});
		}
		// store session cookie
		gen_session(user, res);
		req.session.user = user;
		//check at some page just jump to home page
		var refer = req.session._loginReferer || '/';
		delete req.session._loginReferer;
		for (var i = 0, len = notJump.length; i !== len; ++i) {
			if (refer.indexOf(notJump[i]) >= 0) {
				refer = '/';
				break;
			}
		}
		res.redirect(refer);
	});
};

// sign out
exports.signout = function (req, res, next) {
	req.session.destroy();
	res.clearCookie(config.auth_cookie_name, {
		path: '/'
	});
	res.redirect(req.headers.referer || '/soft/');
};

// private
function gen_session(user, res) {
	var auth_token = encrypt(user._id + '\t' + user.name + '\t' + user.pass + '\t' + user.email, config.session.secret);
	res.cookie(config.auth_cookie_name, auth_token, {
		path: '/',
		maxAge: 1000 * 60 * 60 * 24 * 30
	}); //cookie 有效期30天
}

exports.gen_session = gen_session;

function encrypt(str, secret) {
	var cipher = crypto.createCipher('aes192', secret);
	var enc = cipher.update(str, 'utf8', 'hex');
	enc += cipher.final('hex');
	return enc;
}

function decrypt(str, secret) {
	var decipher = crypto.createDecipher('aes192', secret);
	var dec = decipher.update(str, 'hex', 'utf8');
	dec += decipher.final('utf8');
	return dec;
}

function md5(str) {
	var md5sum = crypto.createHash('md5');
	md5sum.update(str);
	str = md5sum.digest('hex');
	return str;
}

function randomString(size) {
	size = size || 6;
	var code_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var max_num = code_string.length + 1;
	var new_pass = '';
	while (size > 0) {
		new_pass += code_string.charAt(Math.floor(Math.random() * max_num));
		size--;
	}
	return new_pass;
}

// console.log(md5('tyk'));